//
//  HLUserAccount.swift
//  weibo-snh
//
//  Created by 黄力 on 15/12/14.
//  Copyright © 2015年 HLTest. All rights reserved.
//

import UIKit

class HLUserAccount: NSObject,NSCoding {
    
    var access_token: String?
    var expires_in: Double = 0 {
        //设置有效时间的同时设置token的过期时间
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var uid: String?
    var name: String?
    var avatar_large: String?
    //保存过期时间
    var expires_date: NSDate?
    
    //利用kvc进行字典转模型
    init(dic: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    //抛出没有找到的key
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //保存数据到沙盒
    func saveToSanbox() {
        //获取沙盒路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("userAccount.plist")
        //保存
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //取出沙盒中保存的数据
    class func getUserAccount () -> HLUserAccount? {
        //获取沙盒路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("userAccount.plist")
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
        //只有当沙盒中由用户数据,而且用户数据没有过期时才使用
        if let user = userAccount as? HLUserAccount{
            if user.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return user
            }
        }
        return nil
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
    //打印
//    override var description :String {
//       return "\(access_token) \(expires_in) \(uid) \(name) \(avatar_large)"
//    }
}
